#include"Sock.hpp"
#include<unistd.h>

void Usage(std::string proc)
{
  cout << "Usage\n\t" << proc <<" server_port" << endl;
  exit(1);
}

void* Routine(void* arg)
{
  int fd = *(static_cast<int*>(arg));
  cout << "fd :" << fd << " " << pthread_self() <<"正在为该连接提供服务" << endl;
  while(1)
  {
     char buf[1024] = {0};
     ssize_t n = read(fd,buf,sizeof(buf) - 1);
     if(n > 0)
     {
       buf[n] = '\0';
       cout << "client#" << buf << endl;
       
       std::string echo =">>>>>>";
       echo += buf;
       echo +="<<<<<<";
       write(fd,echo.c_str(),echo.size());
     }
     else if(n == 0)
     {
       cout <<"client quit ..." << endl;
       close(fd);
       break;
     }
     else 
     {
       cout <<"error!!!" << endl;
       close(fd);
       break;
     }
  }
  return nullptr;
}

int main(int argc,char* argv[])
{
  if(argc != 2)
  {
    Usage(argv[0]);
  }
  uint16_t port = atoi(argv[1]);
  int listen_sock = Sock::Socket();
  Sock::Bind(listen_sock,port);
  Sock::Listen(listen_sock);
  
  for(;;)
  {
    int fd = Sock::Accept(listen_sock);
    if(fd >= 0)
    {
      pthread_t tid;
      int* new_sock = new int(fd);
      pthread_create(&tid,nullptr,Routine,(void*)new_sock);
    }
  }
  return 0;
}
